#!/usr/bin/env python3
"""
智能体路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db, Agent
import time
import random
import string

bp = Blueprint('agents', __name__)

def generate_agent_id():
    """生成唯一的智能体 ID"""
    timestamp = int(time.time() * 1000)
    random_str = ''.join(random.choices(string.ascii_lowercase + string.digits, k=9))
    return f"agent-{timestamp}-{random_str}"

@bp.route('/', methods=['GET'])
@jwt_required()
def get_agents():
    """获取当前用户的所有智能体"""
    try:
        current_user_id = int(get_jwt_identity())
        agents = Agent.query.filter_by(user_id=current_user_id).order_by(Agent.created_at.desc()).all()
        
        return jsonify({
            'agents': [agent.to_dict() for agent in agents]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/', methods=['POST'])
@jwt_required()
def create_agent():
    """创建新智能体"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('name') or not data.get('url'):
            return jsonify({'error': '名称和URL为必填项'}), 400
        
        agent = Agent(
            id=generate_agent_id(),
            user_id=current_user_id,
            name=data['name'],
            url=data['url'],
            description=data.get('description', ''),
            icon=data.get('icon', 'MessageSquare')
        )
        
        db.session.add(agent)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'agent': agent.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/<agent_id>', methods=['GET'])
@jwt_required()
def get_agent(agent_id):
    """获取单个智能体"""
    try:
        current_user_id = int(get_jwt_identity())
        agent = Agent.query.filter_by(id=agent_id, user_id=current_user_id).first()
        
        if not agent:
            return jsonify({'error': '智能体不存在'}), 404
        
        return jsonify({
            'agent': agent.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/<agent_id>', methods=['PUT'])
@jwt_required()
def update_agent(agent_id):
    """更新智能体"""
    try:
        current_user_id = int(get_jwt_identity())
        agent = Agent.query.filter_by(id=agent_id, user_id=current_user_id).first()
        
        if not agent:
            return jsonify({'error': '智能体不存在'}), 404
        
        data = request.get_json()
        
        if 'name' in data:
            agent.name = data['name']
        if 'url' in data:
            agent.url = data['url']
        if 'description' in data:
            agent.description = data['description']
        if 'icon' in data:
            agent.icon = data['icon']
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'agent': agent.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/<agent_id>', methods=['DELETE'])
@jwt_required()
def delete_agent(agent_id):
    """删除智能体"""
    try:
        current_user_id = int(get_jwt_identity())
        agent = Agent.query.filter_by(id=agent_id, user_id=current_user_id).first()
        
        if not agent:
            return jsonify({'error': '智能体不存在'}), 404
        
        db.session.delete(agent)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '智能体已删除'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

